<?php defined('SYSPATH') OR die('No direct access allowed.');

class WB_Controller extends Template_Controller {
	
	protected $table = null;

	/**
	 * Constructor of  WB_Controller
	 */
	public function __construct($table=FALSE, $db_init=null, $yaml=null)
	{
		parent::__construct();
		
		if ($this->uri->segment(2)=='ajax_form') $this->wb_template->clear_all();
		
		if ($table) 
		{
			$this->set_table($table);
			$this->set_db($db_init);
			$yaml = $this->load_yaml($yaml ? $yaml : $table.'_form');
			$this->set_form($yaml);
		}
		
	}
	
	public function set_table($table)
	{
		$this->table = $table;
	}
	
	public function set_db($db_init=null)
	{
		if (is_null($db_init)) $db_init = array();
		$db_init['table'] = isset($db_init['table']) ? $db_init['table'] : $this->table;
			
		$this->wb_db->initialize($db_init);
	}
	
	public function set_form($form, $primary_key='id', $primary_params=null)
	{
		if ( ! empty($primary_params)) $this->wb_form->initialize($this->table, $primary_key, $primary_params);
		$this->wb_form->build($form, $this->table);
	}
	
	public function load_yaml($yaml)
	{
		require_once Kohana::find_file('vendor','Spyc', TRUE);
		return Spyc::YAMLLoad(APPPATH.'definitions/'.Kohana::config('locale.language.0').$yaml.'.yml');
	}

	/**
	 * Index page
	 */
	public function index()
	{
		$this->session->delete('search', 'order_string', 'order_array', 'uri_string');
		url::redirect($this->uri->rsegment(1).'/overview');
	}
	
	public function overview($page=1)
	{
		$this->wb_db->set_orderby($this->session->get('order_string'));
		
		$this->wb_template->js('simple_table');
		$this->wb_template->js_var('controller_url', url::site($this->uri->rsegment(1)).'/');
		$this->wb_template->js_var('lang', array('confirm_delete' => Kohana::lang('table.confirm_delete')));
		
		$table_view = new View(Kohana::config('admin.template').'/moduls/simple_table/layout');
		$table_view->head = $this->wb_db->populate_head();
		$table_view->tbody = new View(Kohana::config('admin.template').'/moduls/simple_table/tbody');
		$table_view->controller_view = new View(Kohana::config('admin.template').'/moduls/simple_table/controller');
		
		$classes = $this->wb_form->collect_data('table_class');
		if ($array = $this->session->get('order_array')) 
		{
			$keys = array_keys($array);
			$classes[$keys[0]] = isset($classes[$keys[0]]) ? $classes[$keys[0]].' first_order' : 'first_order';
		}
		foreach ($classes as $name=>$class) $classes[$name] = empty($classes[$name]) ? '' : ' class="'.$classes[$name].'"';
		$table_view->classes = $classes;
		$table_view->tbody->classes = $classes;
		$table_view->tbody->head_count = count($table_view->head);
		
		$table_view->tbody->result = $this->wb_db->populate_table($page);
		$table_view->pagination = new Pagination(array(
				'base_url'    => $this->table.'/'.($this->uri->segment(2) ? $this->uri->segment(2) : 'overview').'/', // base_url will default to current uri
				//'uri_segment'    => 'page', // pass a string as uri_segment to trigger former 'label' functionality
				'total_items'    => $this->wb_db->populate_last_max(), // use db count query here of course
				'items_per_page' => $this->wb_db->get_limit(), // it may be handy to set defaults for stuff like this in config/pagination.php
				'style'          => 'digg' // pick one from: classic (default), digg, extended, punbb, or add your own!
			)
		);
		$this->template->main[] = $table_view;
		
		
		$this->session->set('uri_string', $this->uri->string());
	}
	
	public function orderby($name)
	{
		$old = (array)$this->session->get('order_array');
		$new = array($name => isset($old[$name]) && $old[$name]=='asc' ? 'desc' : 'asc');
		foreach ($old as $k=>$v) if ($name!=$k) $new[$k] = $v;
		$this->session->set('order_array', $new);
		$this->session->set('order_string', $this->wb_db->set_orderby($new));
		url::redirect($this->session->get('uri_string'));
	}
	
	public function trashed($page=1)
	{
		if ( ! $this->wb_db->get_trashable())
		{
			$this->user_messages->add(Kohana::lang('admin.not_trashable'), 'alert');
			url::redirect($this->session->get('uri_string'));
		}
		
		$this->wb_db->use_trash();
		
		$this->overview($page);
	}
	
	public function search($page=1)
	{
		$this->wb_db->set_where();
		$this->session->set('search', $this->uri->string());
		$this->overview();
	}
	
	
	
	public function trash($id)
	{
		$this->execute_trash($id);
	}
	
	public function untrash($id)
	{
		$this->wb_db->use_trash();
		$this->execute_untrash($id);
	}
	
	// TODO: delete confirmation
	public function delete($id=null)
	{
		/*$msg = new View(Kohana::config('admin.template').'/moduls/simple_confirm');
		$msg->msg = Kohana::lang('admin.really_delete', count($this->session->get('del_items')));
		$msg->ok = 'execute_delete';
		$msg->no = 'no_delete';
		$this->template->main[] = $msg;*/
		$this->execute_delete($id);
	}
	
	public function execute_trash($id=null, $return=FALSE)
	{
		$trash = is_numeric($id) ?
			array($id) :
			(
				is_array($id) ?
				$id :
				(
					$this->input->post('trash_items') ?
					$this->input->post('trash_items') :
					$this->session->get('trash_items')
				)
			);
		$count = $this->wb_db->trash_all($trash);
		
		if ($return) return $count;
		else url::redirect($this->session->get('uri_string'));
	}
	public function execute_untrash($id=null, $return=FALSE)
	{
		$untrash = is_numeric($id) ?
			array($id) :
			(
				is_array($id) ?
				$id :
				(
					$this->input->post('untrash_items') ?
					$this->input->post('untrash_items') :
					$this->session->get('untrash_items')
				)
			);
		$this->wb_db->use_trash();
		$count = $this->wb_db->untrash_all($untrash);
		
		if ($return) return $count;
		else url::redirect($this->session->get('uri_string'));
	}
	public function execute_delete($id=null, $return=FALSE)
	{
		if ($this->wb_db->get_trashable()) $this->wb_db->use_trash();
		
		$delete = is_numeric($id) ?
			array($id) :
			(
				is_array($id) ?
				$id :
				(
					$this->input->post('del_items') ?
					$this->input->post('del_items') :
					$this->session->get('del_items')
				)
			);
		$count = $this->wb_db->delete_all($delete);
		
		if ($return) return $count;
		else url::redirect($this->session->get('uri_string'));
	}
	public function no_delete()
	{
		$this->session->delete('del_items');
		$this->_last_page();
	}
	
	
	
	public function add()
	{
		if ( ! $this->wb_db->get_addable())
		{
			$this->user_messages->add(Kohana::lang('admin.not_addable'), 'alert');
			url::redirect($this->session->get('uri_string'));
		}
		
		if ($this->input->post())
		{
			$post = array_merge($this->input->post(), $_FILES);
			$result = $this->wb_db->set_item($post);
			if ($result!==FALSE) 
			{
				if ($result) $this->user_messages->add(Kohana::lang('admin.added_msg', $result));
				else $this->user_messages->add(Kohana::lang('admin.nochange_msg'), 'alert');
				url::redirect($this->session->get('uri_string'));
			}
		}
		$form_view = new View(Kohana::config('admin.template').'/moduls/simple_form');
		$form_view->form = $this->wb_form;
		$this->template->main[] = $form_view;
		Event::run('wb_controller.pre_render_form');
	}
	public function edit($id=null)
	{
		if ( ! $this->wb_db->get_editable())
		{
			$this->user_messages->add(Kohana::lang('admin.not_editable'), 'alert');
			url::redirect($this->session->get('uri_string'));
		}
		
		if (is_null($id))
		{
			$this->user_messages->add(Kohana::lang('admin.edit_id_missing'), 'alert');
			url::redirect($this->session->get('uri_string'));
		}
		
		if ($this->input->post())
		{
			$post = array_merge($this->input->post(), $_FILES);
			$result = $this->wb_db->set_item($post, $id);
			if ($result!==FALSE) 
			{
				if ($result) $this->user_messages->add(Kohana::lang('admin.edited_msg', $result));
				else $this->user_messages->add(Kohana::lang('admin.nochange_msg'), 'alert');
				url::redirect($this->session->get('uri_string'));
			}
		}
		elseif ( ! $this->wb_db->populate_form($id)) url::redirect($this->session->get('uri_string'));
		
		$form_view = new View(Kohana::config('admin.template').'/moduls/simple_form');
		$form_view->form = $this->wb_form;
		$this->template->main[] = $form_view;	
		Event::run('wb_controller.pre_render_form');
	}
	
	
	
	
	public function _last_page()
	{
		url::redirect($this->session->get('uri_string'));
	}
	
	public function ajax_form()
	{
		$this->auto_render = FALSE;
		if ($this->input->post())
		{
			$result = $this->wb_db->set_item($this->input->post());
			if ($result) 
			{
				$this->user_messages->add(Kohana::lang('admin.added_msg', $result));
			}
		}
		if (empty($result))
		Event::run('wb_controller.pre_render_form');
		
		$form_view = new View(Kohana::config('admin.template').'/moduls/ajax_form');
		$form_view->form = $this->wb_form;
		
		$form_view->messages = $this->user_messages->render();
		
		$header_view = $this->wb_template->render();
		
	}
	
	public function ajax_handler()
	{
		$this->auto_render = FALSE;
		
		$count = 'nothing happened.';
		if ($this->uri->segment(3)=='undo')
		{
			$_POST = array();
			$undo = $this->session->get_once('undo');
			if (is_array($undo)) $_POST[key($undo)] = current($undo);
		}
		if (isset($_POST['trash_items']))
		{
			$trash = explode(',', $this->input->post('trash_items'));
			$count = $this->execute_trash($trash, TRUE);
			if ($count) $this->session->set('undo', array('trash_items' => $trash));
		}
		elseif (isset($_POST['untrash_items']))
		{
			$untrash = explode(',', $this->input->post('untrash_items'));
			$count = $this->execute_untrash($untrash, TRUE);
			if ($count) $this->session->set('undo', array('untrash_items' => $untrash));
		}
		elseif (isset($_POST['del_items']))
		{
			$del_items = explode(',', $this->input->post('del_items'));
			$count = $this->execute_delete($del_items, TRUE);
		}
		
		
		echo $count, '|';
		if ($count)
		{
			$url = explode('/',$this->session->get('uri_string'));
			$page = is_numeric(end($url)) ? end($url) : 1;
			
			$this->wb_db->set_orderby($this->session->get('order_string'));
			$tbody = new View(Kohana::config('admin.template').'/moduls/simple_table/tbody');
			$classes = $this->wb_form->collect_data('table_class');
			if ($array = $this->session->get('order_array')) 
			{
				$keys = array_keys($array);
				$classes[$keys[0]] = isset($classes[$keys[0]]) ? $classes[$keys[0]].' first_order' : 'first_order';
			}
			foreach ($classes as $name=>$class) $classes[$name] = empty($classes[$name]) ? '' : ' class="'.$classes[$name].'"';
			$tbody->classes = $classes;
			$tbody->head_count = count($this->wb_db->populate_head());
			$tbody->result = $this->wb_db->populate_table($page);
			echo $tbody->render();
		}
		else
		{
			echo Kohana::lang('admin.nochange');
		}
	}
}

//End of WB_Controller